package com.sangu.dianxiu.ui;

import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.sangu.dianxiu.BaseApp;
import com.sangu.dianxiu.ICallBack;
import com.sangu.dianxiu.R;
import com.sangu.dianxiu.adapter.FrequentContactsAdapter;
import com.sangu.dianxiu.bean.user.AddContactsEntity;
import com.sangu.dianxiu.bean.user.ContactEntity;
import com.sangu.dianxiu.config.Constants;
import com.sangu.dianxiu.utils.UserManager;

import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.HashMap;

public class FrequentContactsActivity extends BaseActivity {


    private FrequentContactsAdapter contactsAdapter;
    private UserManager userManager=new UserManager();
    private MyDataSetObserver myDataSetObserver=new MyDataSetObserver();
    private ArrayList<ContactEntity.ContactsEntity> contacts=new ArrayList<>();
    @ViewInject(R.id.et_activity_frequentcontacts_name)     //使用XUtils的注解框架，这样就不用findViewById了
    private EditText etName;
    @ViewInject(R.id.et_activity_frequentcontacts_phone)
    private EditText etPhone;
    @ViewInject(R.id.btn_activity_frequentcontacts_submit)
    private Button btnSubmit;
    @ViewInject(R.id.lv_activity_frequentcontacts_contacts)
    private ListView lvContacts;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frequentcontacts);
        ViewUtils.inject(this);
        init();
        loadContacts();     //加载联系人
    }
    //
    private void init() {
        contactsAdapter=new FrequentContactsAdapter(contacts,this);
        lvContacts.setAdapter(contactsAdapter);
        lvContacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent();
                intent.putExtra("contactId",contacts.get(position).getId()+"");
                intent.putExtra("contactName",contacts.get(position).getName());
                setResult(Constants.REQUEST_CODE_CONTACT_SELECT, intent);
                FrequentContactsActivity.this.finish();
            }
        });
    }

    private void loadContacts() {
        HashMap<String,String> map=new HashMap<>();
        map.put("userId", BaseApp.user.getUserId() + "");
        userManager.getContacts(map, new ICallBack() {
            @Override
            public void onSuccess(String string) {
                ContactEntity entity = JSONObject.parseObject(string, ContactEntity.class);
                if (entity.getRc() == 0)
                {
                    contacts.addAll(entity.getContacts());
                    contactsAdapter.notifyDataSetChanged();
                    contactsAdapter.registerDataSetObserver(myDataSetObserver);             //给adapter注册观察者，这样当adapter数据变化的时候，可以重新加载数据，更新listview
                }

            }

            @Override
            public void onError(VolleyError error) {

            }
        });
    }


    @OnClick({R.id.iv_activity_frequentcontact_back,R.id.btn_activity_frequentcontacts_submit})
    public void onClick(View view){
        switch (view.getId())
        {
            case R.id.iv_activity_frequentcontact_back:
                finish();
                break;
            case R.id.btn_activity_frequentcontacts_submit:
                submit();
                break;
        }
    }

    private void submit() {
        if(TextUtils.isEmpty(etName.getText().toString())||TextUtils.isEmpty(etPhone.getText().toString()))
        {
            Toast.makeText(this,"姓名或手机号码不能为空",Toast.LENGTH_SHORT).show();
        }else{
            HashMap<String,String> map=new HashMap<>();
            map.put("userId", BaseApp.user.getUserId()+"");
            map.put("name",etName.getText().toString());
            map.put("phone",etPhone.getText().toString());
            userManager.addContacts(map, new ICallBack() {
                @Override
                public void onSuccess(String string) {
                    AddContactsEntity entity = JSONObject.parseObject(string, AddContactsEntity.class);
                    if (entity.getRc() == 0) {      //提交成功后重新加载联系人
                        contacts.clear();
                        contactsAdapter.unregisterDataSetObserver(myDataSetObserver);       //提交成功后要取消注册观察者，否则会出现循环
                        loadContacts();
                    }
                }

                @Override
                public void onError(VolleyError error) {

                }
            });
        }
    }
    //当销毁ACtivity的时候取消网络请求，这也正是volley框架的优点之一
    @Override
    protected void onDestroy() {
        super.onDestroy();
        userManager.requestQueue.cancelAll(UserManager.class);
    }
    class MyDataSetObserver extends DataSetObserver {
        @Override
        public void onChanged() {
            super.onChanged();
            contactsAdapter.unregisterDataSetObserver(myDataSetObserver);           //在重新加载数据的时候要取消注册观察者，否则会出现循环
            contacts.clear();
            loadContacts();
        }
    }
}
